package org.linlinjava.litemall.brand.web;

        import com.github.pagehelper.PageInfo;
        import org.apache.commons.lang3.StringUtils;
        import org.linlinjava.litemall.brand.annotation.LoginUser;
        import org.linlinjava.litemall.core.util.JacksonUtil;
        import org.linlinjava.litemall.core.util.MD5Util;
        import org.linlinjava.litemall.core.util.ResponseUtil;
        import org.linlinjava.litemall.db.domain.LitemallDisputeOrder;
        import org.linlinjava.litemall.db.domain.LitemallOrder;
        import org.linlinjava.litemall.db.service.LitemallDisputeService;
        import org.linlinjava.litemall.db.service.LitemallOrderReportService;
        import org.linlinjava.litemall.db.service.LitemallOrderService;
        import org.linlinjava.litemall.db.service.LitemallServiceService;
        import org.linlinjava.litemall.db.util.DisputeConstant;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.*;
        import org.springframework.web.multipart.MultipartFile;
        import javax.servlet.http.HttpServletRequest;
        import java.io.File;
        import java.math.BigDecimal;
        import java.util.LinkedHashMap;
        import java.util.List;
        import java.util.Map;
        import java.util.Random;

/**
 * 争议服务
 */
@RestController
@RequestMapping("service/dispute")
public class ServiceDisputeController {
    @Autowired
    LitemallDisputeService disputeService;
    @Autowired
    LitemallOrderService orderService;
    @Autowired
    LitemallServiceService serviceService;
    @Autowired
    LitemallOrderReportService reportService;

    /**
     * 获取 当前用户的争议单 信息
     * @param msg
     * @param userId
     * @return
     */
    @PostMapping("list")
    public Object list(@RequestBody String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        Integer page = JacksonUtil.parseInteger(msg, "page");
        Integer pageSize = JacksonUtil.parseInteger(msg, "pageSize");
        if (page == null || pageSize == null) {
            return ResponseUtil.badArgument();
        }
        if (page < 0 || pageSize < 0) {
            return ResponseUtil.badArgumentValue();
        }
        String user = JacksonUtil.parseString(msg, "user");
        String brand = JacksonUtil.parseString(msg, "brand");
        PageInfo<LitemallDisputeOrder> orderPageInfo = disputeService.queryOrder(user, brand, page, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("list", orderPageInfo.getList());
        map.put("totalNum", orderPageInfo.getTotal());
        return ResponseUtil.ok(map);
    }

    /**
     * 争议的规则
     * @param msg  争议ID:是争议的理由
     * @param userId 是商户的ID 根据  http://lnzbfz.slzhjc.com  的lnzbfz 决定商户userID
     * @return
     */
    @PostMapping("rule")
    public Object rule(@RequestBody String msg, @LoginUser Integer userId) {
        Integer disputeId = JacksonUtil.parseInteger(msg, "disputeId");
        Boolean support = JacksonUtil.parseBoolean(msg, "support");
        String reason = JacksonUtil.parseString(msg, "reason");
        List<String> picList = JacksonUtil.parseStringList(msg, "picList");
        if (disputeId == null || support == null) {
            return ResponseUtil.badArgument();
        }
        Integer belong = serviceService.getBelong(userId);
        if (belong > 0) {
            return ResponseUtil.unauthz();
        }
        LitemallDisputeOrder disputeOrder = disputeService.findOrderById(disputeId);
        boolean legalState1 = (disputeOrder.getState().equals(DisputeConstant.INTERVENED));
        boolean legalState2 = (disputeOrder.getState().equals(DisputeConstant.RECHECKING));
        if (!legalState1 && !legalState2) {
            return ResponseUtil.fail(403, "该订单不处于合法状态");
        }
        disputeService.rule(disputeOrder, support, reason, picList);
        return ResponseUtil.ok();
    }

    /**
     * 用户订单不合法状态: 已经交易完成,不能出尔反尔
     * @param msg 价格, ID , 理由, 图片
     * @param userId 是商户的ID,并不是用户 根据  http://lnzbfz.slzhjc.com  的lnzbfz 决定商户userID
     * @return
     */
    @PostMapping("recheck")
    public Object recheck(@RequestBody String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        BigDecimal recheckPrice = JacksonUtil.parseDecimal(msg, "price");
        Integer disputeId = JacksonUtil.parseInteger(msg, "id");
        String reason = JacksonUtil.parseString(msg, "reason");
        List<String> picList = JacksonUtil.parseStringList(msg, "picList");
        if (disputeId == null ) {
            return ResponseUtil.badArgument();
        }
        LitemallDisputeOrder disputeOrder = disputeService.findOrderById(disputeId);
        boolean legalState = (disputeOrder.getState().equals(DisputeConstant.INTERVENED));
        if (!legalState) {
            return ResponseUtil.fail(403, "该订单不处于合法状态");
        }
        boolean legalEnsure = disputeOrder.getType().equals(DisputeConstant.TYPE_CORRECT_INSURANCE);
        boolean legalNoEnsure = disputeOrder.getType().equals(DisputeConstant.TYPE_CORRECT) && recheckPrice != null && recheckPrice.compareTo(new BigDecimal(0)) > 0;

        if (!legalNoEnsure && !legalEnsure) {
            return ResponseUtil.fail(403, "请核查您的请求");
        }
        if (legalNoEnsure) {
            disputeOrder.setPayAmount(recheckPrice);
        }
        disputeService.recheck(disputeOrder, legalEnsure, reason, picList);
        return ResponseUtil.ok();
    }

    @PostMapping("upload")
    public Object upload(HttpServletRequest request, @RequestParam(value = "file") MultipartFile file,
                         @RequestParam String msg, @LoginUser Integer userId) {
        Integer belong = serviceService.getBelong(userId);
        if (belong == null || belong > 0) {
            return ResponseUtil.unauthz();
        }
        Integer disputeId = JacksonUtil.parseInteger(msg, "id");
        String reason = JacksonUtil.parseString(msg, "reason");
        if (disputeId == null || disputeId < 1) {
            return ResponseUtil.badArgument();
        }
        try {
            saveFile(file, JacksonUtil.parseString(msg, "fileName"), disputeId, request);
            disputeService.recording(disputeId, reason, null, (short)3);
            return ResponseUtil.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(500, e.toString());
        }
    }

    private void saveFile(MultipartFile file, String fileName, Integer disputeId, HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("utf-8");
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            String type = originalFilename.contains(".") ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1) : null;
            if (StringUtils.isEmpty(type) || "docx".equalsIgnoreCase(type) || "doc".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type)) {
                throw new Exception("文档格式不正确");
            }
            {
                String name = "report" + System.currentTimeMillis() + "_" + new Random().nextInt() + "." + type;
                String realPath = System.getProperty("user.dir");
                String path = realPath + "/dispute/" + name;
                File dir = new File(realPath + "/dispute");
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                file.transferTo(new File(path));
                if (fileName == null) {
                    fileName = originalFilename;
                }
                reportService.insert(name, "dispute", disputeId, fileName, MD5Util.getMD5(file.getInputStream()));
            }
        }
    }
}
